package com.voxel.sense.infomsg.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.nearby.NearbyInfo;
import com.amap.api.services.nearby.NearbySearch;
import com.amap.api.services.nearby.NearbySearchFunctionType;
import com.amap.api.services.nearby.NearbySearchResult;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnDismissListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.example.com.common.app.BaseActivity;
import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.L;
import com.example.com.common.utils.TimeUtils;
import com.example.com.common.utils.ToastUtil;
import com.example.com.common.utils.constants.TimeConstants;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.net.helper.TaskManagerNetHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.response.ConfigEntity;
import cyy.example.com.facotry.model.api.response.TaskActionGroupEntity;
import cyy.example.com.facotry.share.SPEngine;

/**
 * Created by ChenYiYao on 2018/1/2.
 * 派发紧急任务
 */

public class SendUrgencyTaskActivity extends BaseActivity implements OnOptionsSelectListener, DataSource.Callback<BaseEntity>, NearbySearch.NearbyListener {
    private final static int ALL_GROUP_PEOPLE = 0;
    private final static int AROUND_GROUP_PEOPLE = 1;

    @BindView(R.id.et_misson_name)
    EditText et_misson_name;    //任务名
    @BindView(R.id.tv_misson_type)
    TextView tv_misson_type;    //任务类型
    @BindView(R.id.tv_misson_firm)
    TextView tv_misson_firm; //任务对象
    @BindView(R.id.rb_around_people)
    RadioButton rb_around_people;   //附近人btn
    @BindView(R.id.rb_all_people)
    RadioButton rb_all_people;  //所有人
    @BindView(R.id.tv_peole_operations)
    TextView tv_peole_operations; //运维组
    @BindView(R.id.tv_peole_patrol)
    TextView tv_peole_patrol;   //巡查组
    @BindView(R.id.tv_peole_other)
    TextView tv_peole_other;    //其它组
    @BindView(R.id.tv_start_time)
    TextView tv_start_time;
    @BindView(R.id.tv_end_time)
    TextView tv_end_time;
    @BindView(R.id.radio_group)
    RadioGroup radio_group;
    private OptionsPickerView mPvCustomOptions;//条件选择器
    private TimePickerView pvTime;//时间选择器

    private SparseArray<TaskActionGroupEntity.BodyBean> mPeopleArray;//分组人员列表
    private List<ConfigEntity.BodyBean.TaskTypesBean> mTaskType;
    private String mCompany; //公司名
    private String mTaskTypeId;//任务类型
    private String[] mSelectPeople = new String[3];//任务类型
    private long mEndTime;//任务开始时间及任务结束时间
    private long mStartTime;
    private boolean mIsAllPeople = true;


    public static void show(Context context, String company) {
        if (TextUtils.isEmpty(company)) {
            return;
        }
        ToastUtil.showToastLong(Factory.app(), "研发中");
        Intent intent = new Intent(context, SendUrgencyTaskActivity.class);
        intent.putExtra(IntentConstants.STRING_TYPE, company);
        context.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //调用销毁功能，在应用的合适生命周期需要销毁附近功能
        NearbySearch.destroy();
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_send_urgency_task;
    }

    @Override
    protected boolean initArgs(Bundle bundle) {
        mCompany = getIntent().getStringExtra(IntentConstants.STRING_TYPE);
        return super.initArgs(bundle);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        initCustomOptionPicker();
        initTimeSelectView();
    }

    @Override
    protected void initData() {
        super.initData();
        tv_misson_firm.setText(mCompany);
        mPeopleArray = new SparseArray<>();
        //获取执行任务人的分组
        showProgressDialog("", false);
        TaskManagerNetHelper.getUserTaskGroup(this);

    }


    @Override
    protected void initEven() {
        radio_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i == R.id.rb_all_people) {
                    mIsAllPeople = true;
                    L.d("获取所有人的分组");
                    TaskActionGroupEntity.BodyBean bodyBean = mPeopleArray.get(ALL_GROUP_PEOPLE);
                    if (bodyBean != null) {
                        //TODO:网络获取数据
                    }
                } else if (i == R.id.rb_around_people) {
                    mIsAllPeople = false;
                    L.d("获取附近的人");
                    //网络获取附近的人数据
                    //获取附近实例（单例模式）
                    double latitude = Double.parseDouble(SPEngine.getSPEngine().getUserInfo().getlatitude());
                    double longgiude = Double.parseDouble(SPEngine.getSPEngine().getUserInfo().getLonggiude());
                    //TODO:这是用于上传位置到高德云服务的代码，主要是作为获取附近人的备选方案，该段代码暂时保留,删除改短代码时，还要删除销毁部分以及回调接口
                    if (latitude != -1 && longgiude != -1) {
                        //设置附近监听
                        try {
                            NearbySearch.getInstance(getApplicationContext()).addNearbyListener(SendUrgencyTaskActivity.this);
                        } catch (AMapException e) {
                            e.printStackTrace();
                        }
                        //设置搜索条件
                        NearbySearch.NearbyQuery query = new NearbySearch.NearbyQuery();
                        //设置搜索的中心点
                        query.setCenterPoint(new LatLonPoint(latitude, longgiude));
                        L.d("latitude：" + latitude + "----longgiude" + longgiude + "---附近的人");
                        //设置搜索的坐标体系
                        query.setCoordType(NearbySearch.AMAP);
                        //设置搜索半径
                        query.setRadius(10000);
                        //设置查询的时间,单位：秒
                        query.setTimeRange(30 * 60);
                        //设置查询的方式驾车还是距离
                        query.setType(NearbySearchFunctionType.DRIVING_DISTANCE_SEARCH);
                        //调用异步查询接口
                        try {
                            NearbySearch.getInstance(getApplicationContext())
                                    .searchNearbyInfoAsyn(query);
                        } catch (AMapException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
    }

    /**
     * 条件选择器初始化，自定义布局
     */
    private void initCustomOptionPicker() {
        mPvCustomOptions = new OptionsPickerBuilder(this, this)
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {//初始化布局
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = v.findViewById(R.id.iv_cancel);
                        //点击完成
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPvCustomOptions.returnData();
                                mPvCustomOptions.dismiss();
                            }
                        });
                        //点击取消
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPvCustomOptions.dismiss();
                            }
                        });
                    }
                })
//                .isDialog(true)
                .build();
    }

    private void initTimeSelectView() {
        //初始化时间选择器的开始及结束时间
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        //正确设置方式 原因：注意事项有说明
        Calendar endDate = Calendar.getInstance();
        endDate.set(2030, 11, 31);

        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                String string = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()));
                if (v.getId() == R.id.tv_start_time) {
                    tv_start_time.setText(string);
                    mStartTime = TimeUtils.getMillis(date, 0, TimeConstants.MSEC);
                } else if (v.getId() == R.id.tv_end_time) {
                    mEndTime = TimeUtils.getMillis(date, 0, TimeConstants.MSEC);
                    if (mEndTime <= mStartTime) {
                        ToastUtil.showToastLong(Factory.app(), "任务结束时间必须大于开始时间");
                        return;
                    }
                    tv_end_time.setText(string);
                }
            }
        })
                .setType(new boolean[]{true, true, true, true, true, false})//分别表示是否显示年，月，日，时，分，秒，默认全部显示
                .setLabel("年", "月", "日", "时", "分", "秒")
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确认")//确认按钮文字
                .setContentTextSize(16)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("选择时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
//                .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
//                .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(selectedDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();
    }

    @OnClick({R.id.tv_misson_type,
            R.id.tv_peole_operations, R.id.tv_peole_patrol,
            R.id.tv_peole_other, R.id.tv_start_time, R.id.tv_end_time, R.id.titlebar_tv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_misson_type://类型选择
                List<String> taskTypeData = getTaskTypeData();
                showOption(taskTypeData, tv_misson_type, "获取任务类型失败");
                break;
            case R.id.tv_peole_operations://运维组员选择
                List<String> operateGroupData = getOperateGroupData();
                showOption(operateGroupData, tv_peole_operations, "该分组暂未分配到人员");
                break;
            case R.id.tv_peole_patrol://巡查组员选择
                List<String> data = getPatrolGroupData();
                showOption(data, tv_peole_patrol, "该分组暂未分配到人员");
                break;
            case R.id.tv_peole_other://其它组员选择
                List<String> executeGroupData = getExecuteGroupData();
                showOption(executeGroupData, tv_peole_other, "该分组暂未分配到人员");
                break;
            case R.id.tv_start_time:
                pvTime.setDate(Calendar.getInstance());
                pvTime.show(tv_start_time);
                break;
            case R.id.tv_end_time:
                if (mStartTime <= 0) {
                    ToastUtil.showToastLong(Factory.app(), "请选择开始时间");
                    return;
                }
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(mStartTime);
                pvTime.setDate(calendar);
                pvTime.show(tv_end_time);
                break;
            case R.id.titlebar_tv_right:
                submitTask();
                break;
        }
    }

    /**
     * 构造巡查组菜单数据
     */
    private List<String> getPatrolGroupData() {
        List<String> list = new ArrayList<>();
        TaskActionGroupEntity.BodyBean bodyBean = mIsAllPeople ?
                mPeopleArray.get(ALL_GROUP_PEOPLE) : mPeopleArray.get(AROUND_GROUP_PEOPLE);
        if (bodyBean == null) {
            return list;
        }
        List<TaskActionGroupEntity.BodyBean.PatrolBean> patrol = bodyBean.getPatrol();
        if (patrol != null) {
            for (TaskActionGroupEntity.BodyBean.PatrolBean opBean : patrol) {
                list.add(opBean.getPatrolPersonName());
            }
        }
        return list;
    }

    /**
     * 构建执行组菜单数据
     */
    private List<String> getExecuteGroupData() {
        List<String> list = new ArrayList<>();
        TaskActionGroupEntity.BodyBean bodyBean = mIsAllPeople ?
                mPeopleArray.get(ALL_GROUP_PEOPLE) : mPeopleArray.get(AROUND_GROUP_PEOPLE);
        if (bodyBean == null) {
            ToastUtil.showToastLong(Factory.app(), "暂无数据");
            return list;
        }
        List<TaskActionGroupEntity.BodyBean.ExecuteBean> execute = bodyBean.getExecute();
        if (execute != null) {
            for (TaskActionGroupEntity.BodyBean.ExecuteBean opBean : execute) {
                list.add(opBean.getExecutePersonName());
            }
        }
        return list;
    }

    /**
     * 构建运维组菜单数据
     */
    private List<String> getOperateGroupData() {
        List<String> list = new ArrayList<>();
        TaskActionGroupEntity.BodyBean bodyBean = mIsAllPeople ?
                mPeopleArray.get(ALL_GROUP_PEOPLE) : mPeopleArray.get(AROUND_GROUP_PEOPLE);
        if (bodyBean == null) {
            ToastUtil.showToastLong(Factory.app(), "暂无数据");
            return list;
        }
        List<TaskActionGroupEntity.BodyBean.OperationBean> operation = bodyBean.getOperation();
        if (operation != null) {
            for (TaskActionGroupEntity.BodyBean.OperationBean opBean : operation) {
                list.add(opBean.getOperationPersonName());
            }
        }
        return list;
    }


    /**
     * 弹出选择器
     */
    private void showOption(List<String> list, final TextView view, String msg) {
        if (list != null && list.size() > 0) {
            view.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.mipmap.ic_drop_selected_icon, 0);
            mPvCustomOptions.setPicker(list);
            mPvCustomOptions.show(view);
            mPvCustomOptions.setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss(Object o) {
                    view.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.mipmap.ic_drop_unselected_icon, 0);
                }
            });

        } else {
            ToastUtil.showToastLong(Factory.app(), msg);
        }
    }

    /**
     * 获取任务类型的数据
     */
    private List<String> getTaskTypeData() {
        List<String> list = new ArrayList<>();
        if (mTaskType == null) {
//            mTaskType = QueryConfigManager.getInstance().getTaskType();
        }

        for (ConfigEntity.BodyBean.TaskTypesBean bean : mTaskType) {
            list.add(bean.getTaskTypeName());
        }
        return list;
    }

    /**
     * 提交任务
     */
    private void submitTask() {
        if (TextUtils.isEmpty(et_misson_name.getText())) {
            ToastUtil.showToastLong(Factory.app(), "请输入任务名称");
        } else if (TextUtils.isEmpty(tv_misson_type.getText())) {
            ToastUtil.showToastLong(Factory.app(), "请选择任务类型");
        } else if (TextUtils.isEmpty(tv_peole_operations.getText())
                && TextUtils.isEmpty(tv_peole_patrol.getText())
                && TextUtils.isEmpty(tv_peole_other.getText())) {
            ToastUtil.showToastLong(Factory.app(), "请选择执行人");
        } else if (TextUtils.isEmpty(tv_start_time.getText())) {
            ToastUtil.showToastLong(Factory.app(), "请任务开始时间");
        } else if (TextUtils.isEmpty(tv_end_time.getText())) {
            ToastUtil.showToastLong(Factory.app(), "请选择任务结束时间");
        } else if (TextUtils.isEmpty(tv_misson_firm.getText())) {
            ToastUtil.showToastLong(Factory.app(), "请选择公司对象");
        } else {
            //TODO:派发任务

        }
    }


    @Override
    public void onOptionsSelect(int options1, int options2, int options3, View v) {
        switch (v.getId()) {
            case R.id.tv_misson_type://类型选择
                List<String> taskTypeData = getTaskTypeData();
                String type = taskTypeData.get(options1);
                mTaskTypeId = mTaskType.get(options1).getTaskTypeId();
                tv_misson_type.setText(type);
                break;
            case R.id.tv_peole_operations://运维组员选择
                TaskActionGroupEntity.BodyBean bodyBean = mIsAllPeople ?
                        mPeopleArray.get(ALL_GROUP_PEOPLE) : mPeopleArray.get(AROUND_GROUP_PEOPLE);
                List<TaskActionGroupEntity.BodyBean.OperationBean> operation = bodyBean.getOperation();
                TaskActionGroupEntity.BodyBean.OperationBean operationBean = operation.get(options1);
//                mCurrentOpePeopleId = operationBean.getOperationPersonId();
                mSelectPeople[0] = operationBean.getOperationPersonId();
                tv_peole_operations.setText(operationBean.getOperationPersonName());
                break;
            case R.id.tv_peole_patrol://巡查组员选择
                TaskActionGroupEntity.BodyBean bodyBean1 = mIsAllPeople ?
                        mPeopleArray.get(ALL_GROUP_PEOPLE) : mPeopleArray.get(AROUND_GROUP_PEOPLE);
                List<TaskActionGroupEntity.BodyBean.PatrolBean> patrol = bodyBean1.getPatrol();
                TaskActionGroupEntity.BodyBean.PatrolBean patrolBean = patrol.get(options1);
                mSelectPeople[1] = patrolBean.getPatrolPersonId();
                tv_peole_patrol.setText(patrolBean.getPatrolPersonName());
                break;
            case R.id.tv_peole_other://其它组员选择
                TaskActionGroupEntity.BodyBean bodyBean2 = mIsAllPeople ?
                        mPeopleArray.get(ALL_GROUP_PEOPLE) : mPeopleArray.get(AROUND_GROUP_PEOPLE);
                List<TaskActionGroupEntity.BodyBean.ExecuteBean> execute = bodyBean2.getExecute();
                TaskActionGroupEntity.BodyBean.ExecuteBean executeBean = execute.get(options1);
                mSelectPeople[2] = executeBean.getExecutePersonId();
                tv_peole_other.setText(executeBean.getExecutePersonName());
                break;
        }
    }

    @Override
    public void onDataLoaded(BaseEntity data, int reqId) {
        dismissProgressDialog();
        if (data.isSuccess()) {
            TaskActionGroupEntity groupEntity = (TaskActionGroupEntity) data;
            if (mIsAllPeople) {
                L.d("从网络拉取回来了分组人员信息");
                mPeopleArray.put(ALL_GROUP_PEOPLE, groupEntity.getBody());
            } else {
                mPeopleArray.put(AROUND_GROUP_PEOPLE, groupEntity.getBody());
            }
        }
    }

    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        dismissProgressDialog();
    }

    @Override
    public void onUserInfoCleared(int i) {

    }

    /**
     * 高德 周边检索的回调函数
     *
     * @param nearbySearchResult 结果
     * @param resultCode         状态码
     */
    @Override
    public void onNearbyInfoSearched(NearbySearchResult nearbySearchResult, int resultCode) {
        //搜索周边附近用户回调处理
        if (resultCode == 1000) {
            if (nearbySearchResult != null &&
                    nearbySearchResult.getNearbyInfoList() != null &&
                    nearbySearchResult.getNearbyInfoList().size() > 0) {
                NearbyInfo nearbyInfo = nearbySearchResult.getNearbyInfoList().get(0);
                L.d("周边搜索结果为size " + nearbySearchResult.getNearbyInfoList().size() + "first：" + nearbyInfo.getUserID() + "" + nearbyInfo.getDistance() + ""
                        + nearbyInfo.getDrivingDistance() + "  " + nearbyInfo.getTimeStamp() + "  " +
                        nearbyInfo.getPoint().toString());
            } else {
                L.d("周边搜索结果为空");
            }
        } else {
            L.d("周边搜索出现异常，异常码为：" + resultCode);
        }
        NearbySearch.destroy();
    }


    @Override
    public void onNearbyInfoUploaded(int i) {

    }
}
